package com.anjbo.controller.loan;

import com.anjbo.aspect.ResultWrapped;
import com.anjbo.bean.loan.LoanScheme;
import com.anjbo.bean.loan.RedMortgageDto;
import com.anjbo.common.Constants;
import com.anjbo.common.Enums;
import com.anjbo.common.RespDataObject;
import com.anjbo.common.RespStatusEnum;
import com.anjbo.exception.ResponseException;
import com.anjbo.service.loan.RedMortgageService;
import com.anjbo.service.order.OrderThirdService;
import com.anjbo.utils.AmsUtil;
import com.anjbo.utils.ConfigUtil;
import com.anjbo.utils.HttpUtil;
import com.anjbo.utils.UidUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.zt.commons.toolkit.ValidateUtils;
import org.zt.commons.toolkit.fs.DefaultFileSystem;
import org.zt.commons.toolkit.fs.FileSystem;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping(value = "/app/loan/mortgage")
public class RedMortgageController {

    private static Log log = LogFactory.getLog(RedMortgageController.class);
    //抵押物 商铺 公寓 写字楼 别墅
    private static final Map<String, String> Collateral = new HashMap<String, String>();

    static {
        Collateral.put("0", "• 商铺");
        Collateral.put("1", "• 公寓");
        Collateral.put("2", "• 写字楼");
        Collateral.put("3", "• 别墅");
    }

    /*询价工具地址*/
    private static final String URL = ConfigUtil.getStringValue(Enums.GLOBAL_CONFIG_KEY.TOOLS_URL.toString());

    @Autowired
    private RedMortgageService redMortgageService;
	@Resource
	private OrderThirdService orderThirdService;

    /*房产预估*/
    @RequestMapping("/assess")
    @ResponseBody
    @ResultWrapped
    public Object assess(RedMortgageDto mortgageDto, @RequestParam(value = "file", required = false) MultipartFile[] files) throws Exception {
        int assess_times_limit = ConfigUtil.getIntegerValue("assess_times_limit");
        if (redMortgageService.assessTimesToday(mortgageDto.getUid()) > (assess_times_limit - 1)) {
            throw new ResponseException("房产预估每天只能三次");
        }

       /* if(!validatePhone(mortgageDto.getPhoneNum())){
            throw new ResponseException("手机号码不正确");
        }*/

        /*if(StringUtils.isNotEmpty(mortgageDto.getChannelManager())){
            String name = redMortgageService.selectUserNameByUid(mortgageDto.getChannelManager());
            mortgageDto.setChannelManager(name);
        }*/

        log.info("房产预估参数:" + mortgageDto.toString());
        if (mortgageDto.getType() == 2) {//非住宅
            mortgageDto.setAssessState(0);
            String urls = (String) fileUpload(files);
            mortgageDto.setHouseCert(urls);
            mortgageDto.setOrderNo(UidUtil.generateOrderId());
            mortgageDto.setProgressId(200);
            int n = redMortgageService.insertRedMortgageDto(mortgageDto);
            sendAssessMessage(mortgageDto);
            log.info("非住宅房产预估成功:" + new Gson().toJson(mortgageDto));
            initProgressItem(mortgageDto.getOrderNo(), "200");
            return null;
        } else if (mortgageDto.getType() == 1) {//住宅
            String qualification = mortgageDto.getQualification();//获取资质
            List<LoanScheme> loanSchemes = redMortgageService.selectSchemeByQualification(qualification);
            mortgageDto.setSchemes(loanSchemes);
            LoanScheme loanScheme = loanSchemes.get(0);
            mortgageDto.setSchemeType(loanScheme.getType());
            mortgageDto.setRepayment(loanScheme.getRepayment());
            mortgageDto.setTerm(loanScheme.getTerm());
            mortgageDto.setRate(Double.valueOf(loanScheme.getRate()));

            String enquiryUrl = URL + "/tools/enquiry/v/createEnquiry";
            HashMap<String, Object> params = new HashMap<String, Object>();
            params.put("type", "2");//2代表同志诚
            params.put("isGetNetPriceTax", 1);
            params.put("uid", mortgageDto.getUid());
            params.put("propertyName", mortgageDto.getPropertyName());
            params.put("propertyId", mortgageDto.getPropertyId());
            params.put("buildingName", mortgageDto.getBuildingName());
            params.put("buildingId", mortgageDto.getBuildingId());
            params.put("roomName", mortgageDto.getRoomName());
            params.put("roomId", mortgageDto.getRoomId());
            params.put("area", mortgageDto.getArea());

            String enquiryResult = HttpUtil.jsonPost(enquiryUrl, params);
            String enquiryid = parseEnquiryId(enquiryResult);
            if (enquiryid == null) {
                throw new RuntimeException("创建查询失败，enquiryid为空");
            }
            enquiryUrl = URL + "/tools/enquiry/v/getEnquiryInfo";
            params.clear();
            params.put("enquiryId", enquiryid);
            String info = HttpUtil.jsonPost(enquiryUrl, params);
            RespDataObject<Map<String, Object>> respData = new Gson().fromJson(info, new TypeToken<RespDataObject<Map<String, Object>>>() {
            }.getType());

            Map<String, Object> data = respData.getData();
            List<Map<String, Object>> enquiryReportList = (List<Map<String, Object>>) data.get("enquiryReportList");
            Map<String, Object> objectMap = enquiryReportList.get(0);
            Double totalPrice = MapUtils.getDouble(objectMap, "totalPrice");
            if (totalPrice > 0) {
                mortgageDto.setAssessState(1);
            } else {
                mortgageDto.setAssessState(0);
            }
            mortgageDto.setAssessAmount(totalPrice);
            mortgageDto.setAvailableAmount(((int) (totalPrice * 0.8 * 100)) / 100);
            mortgageDto.setOrderNo(UidUtil.generateOrderId());//生成订单

            mortgageDto.setStatus(0);//表示预估状态
            mortgageDto.setProgressId(200);
            int n = redMortgageService.insertRedMortgageDto(mortgageDto);
            initProgressItem(mortgageDto.getOrderNo(), "200");
            log.info("住宅房产预估成功:" + new Gson().toJson(mortgageDto));
            Map<String, Object> toMap = objectToMap(mortgageDto);
            return toMap;
        } else {
            throw new ResponseException("抵押类型有误");
        }
    }


    /*房产预估历史*/
    @RequestMapping("/assess/history")
    @ResponseBody
    @ResultWrapped
    public Object assessHistory(@RequestBody RedMortgageDto mortgageDto) {
        List<RedMortgageDto> list = redMortgageService.getHistoryListByUid(mortgageDto);
        if(list!=null){
            for(RedMortgageDto dto:list){
                String createTime = dto.getCreateTime();
                dto.setCreateTime(createTime.substring(0,createTime.lastIndexOf(".")));
            }
        }
        return list;
    }

    /*房产预估详情*/
    @RequestMapping("/assess/detail")
    @ResponseBody
    @ResultWrapped
    public Object assessDetail(@RequestBody RedMortgageDto mortgageDto) {
        String orderNo = mortgageDto.getOrderNo();
        RedMortgageDto redMortgageDto = redMortgageService.getRedMortgageDtoByOrderId(orderNo);
        List<LoanScheme> loanSchemes = redMortgageService.selectSchemeByType(redMortgageDto.getSchemeType());
        redMortgageDto.setSchemes(loanSchemes);
        Map<String, Object> toMap = objectToMap(redMortgageDto);
        return toMap;
    }

    /*图片上传接口*/
    @RequestMapping("/assess/upload")
    @ResponseBody
    @ResultWrapped
    public Object fileUpload(@RequestParam("file") MultipartFile[] files) throws IOException {
        Assert.isTrue((files != null && files.length > 0), "图片不能为空");
        FileSystem fileSystem = new DefaultFileSystem();
        StringBuffer urls = new StringBuffer();
        String[] cards = {" ", " "};
        for (MultipartFile file : files) {
            log.info("上传文件名为：" + file.getOriginalFilename());
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            log.info("上传文件扩展名为：" + extension);
            if (StringUtils.isBlank(extension)) {
                extension = "jpg";
            }
            File tempFile = File.createTempFile(UUID.randomUUID().toString(), "." + extension);
            file.transferTo(tempFile);
            String url = fileSystem.upload(tempFile);
            if (file.getOriginalFilename().startsWith("card")) {
                if (file.getOriginalFilename().startsWith("card0")) {
                    cards[0] = url;
                } else if (file.getOriginalFilename().startsWith("card1")) {
                    cards[1] = url;
                }
            } else {
                urls.append(url).append(";");
            }
            tempFile.delete();
        }
        if (files[0].getOriginalFilename().startsWith("card")) {
            return cards[0] + ";" + cards[1];
        } else {
            return urls.deleteCharAt(urls.lastIndexOf(";")).toString();
        }
    }

    /*多图片上传接口*/
    @RequestMapping("/assess/multupload")
    @ResponseBody
    @ResultWrapped
    public Object multFileUpload(RedMortgageDto mortgageDto, @RequestParam("file") MultipartFile[] files) throws IOException {
        System.out.println("请求来了，orderNo=" + mortgageDto.getOrderNo() + ":::" + files.length);

        RedMortgageDto dto = redMortgageService.selectByOrderNo(mortgageDto.getOrderNo());
        String houseCert = mortgageDto.getHouseCert();
        String creditReportImage = mortgageDto.getCreditReportImage();

        String cardImage = mortgageDto.getCardImage();

        List<MultipartFile> houseCerts = new ArrayList<MultipartFile>();
        List<MultipartFile> creditReportImages = new ArrayList<MultipartFile>();

        List<MultipartFile> cardImages = new ArrayList<MultipartFile>();

        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            if (fileName.startsWith("house")) {
                houseCerts.add(file);
            } else if (fileName.startsWith("credit")) {
                creditReportImages.add(file);
            } else if (fileName.startsWith("card")) {
                cardImages.add(file);
            }
        }
        if (houseCerts.size() > 0) {
            String urls = (String) fileUpload(houseCerts.toArray(new MultipartFile[houseCerts.size()]));
            if (StringUtils.isEmpty(houseCert)) {
                houseCert = urls;
            } else {
                houseCert = houseCert + ";" + urls;
            }
        }
        if (creditReportImages.size() > 0) {
            String urls = (String) fileUpload(creditReportImages.toArray(new MultipartFile[creditReportImages.size()]));
            if (StringUtils.isEmpty(creditReportImage)) {
                creditReportImage = urls;
            } else {
                creditReportImage = creditReportImage + ";" + urls;
            }
        }
        if (cardImages.size() > 0) {
            String urls = (String) fileUpload(cardImages.toArray(new MultipartFile[cardImages.size()]));
            if (StringUtils.isEmpty(cardImage)) {
                cardImage = urls;
            } else {
                cardImage = merge(cardImage, urls);
            }
        }
        if (mortgageDto.getImgType() != null && mortgageDto.getImgType().equals("house") && mortgageDto.getClearUp() != null && mortgageDto.getClearUp() == 1) {
            redMortgageService.cleanHouseCert(mortgageDto.getOrderNo());
            return null;
        } else if (mortgageDto.getImgType() != null && mortgageDto.getImgType().equals("credit") && mortgageDto.getClearUp() != null && mortgageDto.getClearUp() == 1) {
            redMortgageService.cleanCredit(mortgageDto.getOrderNo());
            return null;
        } else if (mortgageDto.getImgType() != null && mortgageDto.getImgType().equals("card") && mortgageDto.getClearUp() != null && mortgageDto.getClearUp() == 1) {
            redMortgageService.cleanCard(mortgageDto.getOrderNo());
            return null;
        }
        mortgageDto.setHouseCert(houseCert);
        mortgageDto.setCreditReportImage(creditReportImage);
        mortgageDto.setCardImage(cardImage);
        mortgageDto.setStatus(dto.getStatus());
        Integer result = redMortgageService.updateRedMortgageDtoByOrderId(mortgageDto);
        return result;
    }

    private String merge(String cardImage, String urls) {
        String[] c = cardImage.split(";");
        String[] u = urls.split(";");
        String[] m = new String[2];
        m[0] = (!u[0].equals(" ")) ? u[0] : c[0];
        m[1] = (!u[1].equals(" ")) ? u[1] : c[1];
        return m[0] + ";" + m[1];
    }

    /*提交申请*/
    /*点击立即申请，后台生成订单的信息，同时发送短信给相关客服人员（限制每个账号每天最多申请三次）*/
    //【快鸽按揭】红本抵押贷款（住宅），基本信息：xxx物业xxx楼栋xxx单元xxx房号；XX㎡；申请借款金额XXX万；资质XXXX；累计逾期6次以下。客户联系电话：18607550755 。
    //【快鸽按揭】红本抵押贷款（此处显示用户之前选的抵押物），基本信息：抵押物类型；已出租；租金90000元；申请借款额200万。客户联系电话：18607550755 。
    @RequestMapping("/assess/submit")
    @ResponseBody
    @ResultWrapped
    public Object submit(@RequestBody RedMortgageDto mortgageDto) {
        String orderNo = mortgageDto.getOrderNo();
        mortgageDto = redMortgageService.getRedMortgageDtoByOrderId(orderNo);
        sendSubmitOrderMessage(mortgageDto);
        mortgageDto.setStatus(1);
        redMortgageService.updateRedMortgageDtoByOrderId(mortgageDto);
        if (mortgageDto.getType() == 1) {
            mortgageDto.setName(mortgageDto.getPropertyName() + mortgageDto.getBuildingName() + mortgageDto.getRoomName());
        } else if (mortgageDto.getType() == 2) {
            mortgageDto.setName(mortgageDto.getCollateral());
        }

        mortgageDto.setProgressId(210);
        mortgageDto.setProgressName("已申请贷款,客服回访中");
        mortgageDto.setType(16);

        int i = redMortgageService.insertOrderThird(mortgageDto);
        //initProgressItem(mortgageDto.getOrderNo(), "210");
        return null;
    }


    /**
     * 订单详情(红本抵押)
     */
    @RequestMapping("/order/detail")
    @ResponseBody
    public RespDataObject<Map<String, Object>> orderDetail(HttpServletRequest request,@RequestBody Map<String, Object> param) {

        RespDataObject<Map<String, Object>> resp = new RespDataObject<Map<String, Object>>();
        Map<String, Object> orderInfo = new HashMap<String, Object>();
        try {
            orderInfo = redMortgageService.getRedMortgageDetailByOrderNo(param);
            List<Map<String, Object>> progressList = redMortgageService.selectRedOrderProgressList();
            Map<String, Object> progressIdMap = orderThirdService.getProgressIdByOrderNo(param);
            orderInfo.put("progressList", progressList);
            orderInfo.put("progressId", MapUtils.getString(progressIdMap, "progressId"));

            //切割照片为数组
            String houseCert = MapUtils.getString(orderInfo, "houseCert");
            String creditReportImage = MapUtils.getString(orderInfo, "creditReportImage");
            String cardImage = MapUtils.getString(orderInfo, "cardImage");
            if (!StringUtils.isEmpty(houseCert)) {
                orderInfo.put("houseCertArray", houseCert.split(";"));
            }
            if (!StringUtils.isEmpty(creditReportImage)) {
                orderInfo.put("creditReportImageArray", creditReportImage.split(";"));
            }
            if (!StringUtils.isEmpty(cardImage)) {
                orderInfo.put("cardImageArray", cardImage.split(";"));
            }
            String[] cardImageArray = (String[]) orderInfo.get("cardImageArray");

            if (cardImageArray == null) {
                orderInfo.put("cardImageArray", " ; ".split(";"));
            } else if (cardImageArray.length == 1) {
                String[] strings = new String[2];
                strings[0] = cardImageArray[0];
                strings[1] = " ";
                orderInfo.put("cardImageArray", strings);
            }

            //将progressId 由int转String
            Integer progressId = MapUtils.getInteger(orderInfo, "progressId");
            Integer state = MapUtils.getInteger(orderInfo, "status");
            if (progressId != null) {
                orderInfo.put("progressId", progressId.toString());
            }
            if (progressList != null && progressList.size() > 0) {
                for (Map<String, Object> progressMap : progressList) {
                    Integer id = MapUtils.getInteger(progressMap, "progressId");
                    if (id != null) {
                    	if(progressId != null &&progressId.equals(id)&&state==2){
            				progressMap.put("progressName", MapUtils.getString(progressMap, "progressName")+"失败");
            			}
                        progressMap.put("progressId", id.toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCode(RespStatusEnum.FAIL.getCode());
            resp.setMsg(RespStatusEnum.FAIL.getMsg());
            return resp;
        }

        resp.setData(orderInfo);
        resp.setCode(RespStatusEnum.SUCCESS.getCode());
        resp.setMsg(RespStatusEnum.SUCCESS.getMsg());

        return resp;

    }

    /**
     * 贷款方案详情(红本抵押)
     */
    @RequestMapping("/scheme/detail")
    @ResponseBody
    public RespDataObject<Map<String, Object>> schemeDetail(HttpServletRequest request, @RequestBody Map<String, Object> param) {

        RespDataObject<Map<String, Object>> resp = new RespDataObject<Map<String, Object>>();
        Map<String, Object> orderInfo = new HashMap<String, Object>();
        try {
            orderInfo = redMortgageService.getRedMortgageDetailByOrderNo(param);
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCode(RespStatusEnum.FAIL.getCode());
            resp.setMsg(RespStatusEnum.FAIL.getMsg());
            return resp;
        }
        resp.setData(orderInfo);
        resp.setCode(RespStatusEnum.SUCCESS.getCode());
        resp.setMsg(RespStatusEnum.SUCCESS.getMsg());
        return resp;
    }

    private String parseEnquiryId(String enquiryResult) {
        JsonParser jsonParser = new JsonParser();
        JsonObject jsonObject = (JsonObject) jsonParser.parse(enquiryResult);
        String code = jsonObject.get("code").getAsString();
        if (!"SUCCESS".equals(code)) {
            return null;
        }
        JsonObject data = jsonObject.get("data").getAsJsonObject();
        String enquiryid = data.get("enquiryid").getAsString();
        return enquiryid;
    }

    private Integer assessTimesToday(String uid) {
        return redMortgageService.assessTimesToday(uid);
    }

    private Map<String, Object> objectToMap(Object object) {
        BeanMap beanMap = new BeanMap(object);
        HashMap<String, Object> map = new HashMap<String, Object>(beanMap);
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        Set<Map.Entry<String, Object>> entries = map.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            if (entry.getValue() instanceof List) {
                resultMap.put(entry.getKey(), entry.getValue());
            } else if (entry.getValue() instanceof Double) {
                NumberFormat formatter = new DecimalFormat("0.00");
                resultMap.put(entry.getKey(), formatter.format(entry.getValue()));
            } else {
                resultMap.put(entry.getKey(), String.valueOf(entry.getValue()));
            }
        }
        return resultMap;
    }

    private void initProgressItem(String orderNo, String code) {
        redMortgageService.initProgressItem(orderNo, code);
    }

    private void sendAssessMessage(RedMortgageDto mortgageDto) {
        StringBuffer sb = new StringBuffer("房产预估请求,基本信息:");
        sb.append(mortgageDto.getCollateral() + ";");
        if (mortgageDto.getIsRental() == 1) {
            sb.append("已出租;租金:" + mortgageDto.getRent() + "元;");
        } else {
            sb.append("未出租;");
        }
        sb.append("申请借款额:" + mortgageDto.getBorrowingAmount() + "万;客户联系电话:" + mortgageDto.getPhoneNum());
        try {
            String ipWhite = ConfigUtil.getStringValue(Enums.GLOBAL_CONFIG_KEY.AMS_SMS_IPWHITE.toString());
            String phone = ConfigUtil.getStringValue("assess_msg_phone");
            AmsUtil.smsSendStr(phone, ipWhite, sb.toString(), Constants.SMS_FLAG_7);
        } catch (Exception e) {
            log.info("非住宅短信发送失败:" + e.getMessage());
        }
    }

    private void sendSubmitOrderMessage(RedMortgageDto mortgageDto) {
        StringBuilder smsContent = new StringBuilder();
        if (mortgageDto.getType() == 2) {//非住宅
            smsContent.append("红本抵押贷款(" + mortgageDto.getCollateral() + "),")
                    .append("基本信息:" + mortgageDto.getCollateral() + ";" + (mortgageDto.getIsRental() == 1 ? "已出租" : "未出租"));
            if (mortgageDto.getIsRental() == 1) {
                smsContent.append(";租金" + mortgageDto.getRent() + "元");
            }
            smsContent.append(";申请借款额" + mortgageDto.getBorrowingAmount() + "万" + ";客户联系电话:" + mortgageDto.getPhoneNum()).toString();
        } else if (mortgageDto.getType() == 1) {//住宅
            smsContent.append("红本抵押贷款(住宅),基本信息:" + mortgageDto.getPropertyName() + mortgageDto.getBuildingName() + mortgageDto.getRoomName())
                    .append(";申请借款金额:" + mortgageDto.getBorrowingAmount() + "万")
                    .append(";资质:" + mortgageDto.getQualification())
                    .append(";累计延期:" + mortgageDto.getOverdueTimes()+";客户联系电话:" + mortgageDto.getPhoneNum()).toString();
        }
        String ipWhite = ConfigUtil.getStringValue(Enums.GLOBAL_CONFIG_KEY.AMS_SMS_IPWHITE.toString());
        //18607550755
        String phone = ConfigUtil.getStringValue("ordersubmit_msg_phone");
        try {
            log.info("发送短信到客服手机(【快鸽按揭】红本抵押贷款)");
            AmsUtil.smsSendStr(phone, ipWhite, smsContent.toString(), Constants.SMS_FLAG_7);
        } catch (Exception e) {
            log.error("发送短信到客户手机失败!" + smsContent);
        }
    }

    private boolean validatePhone(String phone){
        Pattern pattern = Pattern.compile("^1[3|4|5|6|7|8|9]\\d{9}$");
        Matcher matcher = pattern.matcher(phone);
        boolean matches = matcher.matches();
        return matches;
    }

}
